package net.lulihu.pangolin.headless.server.component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.pangolin.headless.common.container.annotation.Component;
import net.lulihu.pangolin.headless.common.container.templet.ApplicationLifeCycle;
import net.lulihu.pangolin.headless.common.container.templet.Initialization;
import net.lulihu.pangolin.headless.server.handler.UserProxyChannelHandler;
import net.lulihu.pangolin.headless.server.metrics.BytesMetricsHandler;

/**
 * 用户代理网络组件
 * <p>
 * 负责监听用户端口 实现数据转发
 */
@Slf4j
@Component
public class UserProxyNetworkComponent extends AbstractNetwork implements Initialization, ApplicationLifeCycle {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    @Override
    public void after() {
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();

        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addFirst(new BytesMetricsHandler());
                        pipeline.addLast(new UserProxyChannelHandler());
                    }
                });
    }

    @Override
    public void applicationShowdown() {
        log.info("用户代理网络组件关闭ing");

        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
